package myPetStore.persistence.impl;

import myPetStore.domain.Category;
import myPetStore.persistence.CategoryDao;
import myPetStore.persistence.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CategoryDaoImpl implements CategoryDao {
    private static final String GET_CATEGORY =
            "SELECT catid AS categoryId,name,descn AS description FROM category WHERE catid=?";
    private static final String GET_CATEGORY_LIST=
            "SELECT catid AS categoryId,name,descn AS description FROM category";
    @Override
    public List<Category> getCategoryList() {
        List<Category> categoryList = new ArrayList<>();
        try {
            Connection connection= DBUtil.getConnection();
            Statement statement=connection.createStatement();
            ResultSet resultSet=statement.executeQuery(GET_CATEGORY_LIST);
            while (resultSet.next()){
                Category category=new Category();
                category.setCategoryId(resultSet.getString("categoryId"));
                category.setDescription(resultSet.getString("description"));
                category.setName(resultSet.getString("name"));
                categoryList.add(category);

            }
            DBUtil.closeResultSet(resultSet);
            DBUtil.closeStatement(statement);
            DBUtil.closeConnection(connection);

        }catch (Exception ex){
            ex.printStackTrace();
        }
        return categoryList;
    }

    @Override
    public Category getCategory(String var1) {
        Category category=null;
        try { Connection connection=DBUtil.getConnection();
            PreparedStatement statement=connection.prepareStatement(GET_CATEGORY);
            statement.setString(1,var1);
            ResultSet resultSet=statement.executeQuery();
            if(resultSet.next()){
                category=new Category();
                category.setCategoryId(resultSet.getString("categoryId"));
                category.setDescription(resultSet.getString("description"));
                category.setName(resultSet.getString("name"));
            }
            statement.close();
            resultSet.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return category;
    }
}
